package com.example.login_captcha_2.redis;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis工具类：封装了StringRedisTemplate
 */
@Component
public class StringRedisUtils {

    private final StringRedisTemplate stringRedisTemplate;

    @Autowired
    public StringRedisUtils(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * get key
     *
     * @param key 键
     * @return String
     */
    public String get(String key) {
        return getValueOperations().get(key);
    }

    /**
     * del key
     *
     * @param key 键
     */
    public void delete(String key) {
        stringRedisTemplate.delete(key);
    }

    public Boolean hasKey(String key) {
        return stringRedisTemplate.hasKey(key);
    }

    /**
     * set key value
     *
     * @param key   键
     * @param value 值
     */
    public void set(String key, String value) {
        getValueOperations().set(key, value);
    }

    /**
     * expire key seconds
     *
     * @param key 键
     */
    public void expire(String key, long timeout, TimeUnit unit) {
        stringRedisTemplate.expire(key, timeout, unit);
    }

    /**
     * key的值自增：incrby key
     *
     * @param key 键
     * @return 自增后的值
     */
    public Long incrBy(String key) {
        return getValueOperations().increment(key);
    }

    /**
     * 获取ValueOperations对象
     *
     * @return ValueOperations<String, String>
     */
    private ValueOperations<String, String> getValueOperations() {
        return stringRedisTemplate.opsForValue();
    }

}